import { Component } from 'react';
import MyLoading from '../../components/loading';
import WithRouter from '../../router/withRouter';
import { getGoodsInfo } from '../../api/info';
import InfoSwiper from '../../components/info/InfoSwiper';
import './index.less'
import InfoMsg from '../../components/info/infoMsg';
import { Arrow, CartO, StarO,ArrowLeft,Star} from '@react-vant/icons';
import Coment from '../../components/info/coment';
import { ImagePreview, Tabs, ActionBar, Toast } from 'react-vant';
import { createRef } from 'react';
import SkuPup from '../../components/info/skuPup';
import Like from '../../components/info/like';
import { userClolet,RemoveClolet } from '../../api/user';
import { getCartList} from '../../api/cart';
class Info extends Component {
    swiperRef = createRef();
    skuRef = createRef();
    state = {
        info: null,
        msgInfo: {
            price: '',
            otPrice: '',
            storeName: "",
            sales: 0,
            stock: 0,
            image: "",
            sku: ""
        },
        imgList: [],
        // 产品属性列表
        productAttr: [],
        // 存放每个属性所选中的属性值索引
        skuList: [],
        // sku规格对应的详情数据对象
        productValue: [],
        userCollect:false,
        cartCount:0
    }
    render() {
        let { info, msgInfo, productAttr, skuList,userCollect,cartCount } = this.state;

        return (
            <div>
                {info && (
                    <div className='info_page'>
                        <div className='left'>
                        <ArrowLeft color='#3f45ff' fontSize={15} onClick={()=>{
                              this.props.router.navigate(-1)
                        }}/>
                        </div>
                        <Tabs
                            sticky
                            scrollspy={{ autoFocusLast: true, reachBottomThreshold: 50 }}
                        >
                            {/* 
                        JSON.parse(info.sliderImage) 将数组字符串转化为数组
                        */}
                            <Tabs.TabPane title={`商品`} defaultActive={0}>
                                <div ref={this.swiperRef}>
                                    <InfoSwiper sliderImage={JSON.parse(info.sliderImage)}></InfoSwiper>
                                </div>
                                <InfoMsg msgInfo={msgInfo}></InfoMsg>
                                <div className="changeAttr" onClick={() => this.changeSku()}>
                                    已选择： <span className="attrNmae">{msgInfo.sku}</span>
                                    <div className="right">
                                        <Arrow />
                                    </div>
                                </div>
                            </Tabs.TabPane>
                            <Tabs.TabPane title='评论'>
                                <Coment></Coment>
                            </Tabs.TabPane>
                            <Tabs.TabPane title='推荐'>
                                <div className='tuijian'>
                                    <div className='title'> 优品推荐</div>
                                    <Like/>
                                </div>
                            </Tabs.TabPane>
                            <Tabs.TabPane title='详情'>
                                <div className='content'>
                                    <div className='title'>
                                        商品详情
                                    </div>
                                    <div dangerouslySetInnerHTML={{
                                        __html: info.content
                                    }} onClick={(e) => this.showImg(e)}></div>
                                </div>
                            </Tabs.TabPane>

                        </Tabs>
                        <div>
                            <ActionBar>
                                <ActionBar.Icon icon={<CartO />} badge={{ content: cartCount }} text='购物车' onClick={()=>{
                                    this.props.router.navigate('/index/cart')
                                }}/>
                                <ActionBar.Icon icon={userCollect?<Star color='rgb(255, 80, 0)'/>:<StarO />} text='收藏' onClick={()=>this.userColllet()}/>
                                <ActionBar.Button type='warning' text='加入购物车' onClick={() => this.changeSku()} />
                                <ActionBar.Button type='danger' text='立即购买' onClick={()=>this.changeSku()}/>
                            </ActionBar>
                        </div>
                        {
                            // 弹出层 sku
                        }
                        <SkuPup ref={this.skuRef} msgInfo={msgInfo} cartCount={cartCount} productAttr={productAttr} skuList={skuList} setSkuList={(skuList) => {
                            this.setState({
                                skuList: skuList,
                            },()=>{
                                this.getSkuInfo();
                            })
                        }} userCollect={userCollect} setCollect={()=>{
                            this.userColllet();
                        }} goCart={()=>{
                            this.props.router.navigate('/index/cart')
                        }} goComfirm={(id)=>{
                            this.props.router.navigate("/conorder",{
                                state:{
                                    id
                                }
                            })
                        }} changeCount={()=>{
                            this.setState({cartCount:cartCount+1})
                        }}/>
                    </div>
                )
                }
                {
                    !info && <MyLoading></MyLoading>
                }
            </div >
        )
    }
    async componentDidMount() {
        // 获取路由动态参数id
        let { id } = this.props.router.params;
        let res1 = await getCartList();
        console.log(id)
        
        // 获取商品详情数据
        let res = await getGoodsInfo(id);
        console.log(res)
        this.state.userCollect = res.data.data.userCollect;
        console.log(0,res.data.data.userCollect);
        let obj={
            userCollect:this.state.userCollect,
            cartCount:res1.data.data.list.length
        }
        this.setState({...obj})
        let productInfo = res.data.data.productInfo;
        // 处理富文本字符串 获取所用图片链接并存放到数组中
        let imgList = []
        productInfo.content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
            imgList.push(capture);
        });
        let scrollHeight = 0;
        //  获取商品规格
        let productAttr = res.data.data.productAttr;
        let skuList = [];
        // 处理商品规格
        productAttr.forEach(item => {
            skuList.push(0)
            item.attrValues = item.attrValues.split(",");
        })
        let productValue = res.data.data.productValue
        this.setState({
            info: productInfo,
            imgList,
            productAttr,
            skuList,
            productValue
        }, () => {
            scrollHeight = this.swiperRef.current.clientHeight;
            this.getSkuInfo();
        })

        // 监听页面滚动
        window.onscroll = () => {
            let scrollTop = document.documentElement.scrollTop;
            let tab = document.querySelector(".rv-sticky");
            if (scrollTop >= scrollHeight) {
                tab.style.display = 'block';
            } else {
                tab.style.display = 'none';
            }
        }
    }
    componentWillUnmount() {
        window.onscroll = null;
    }
    // 预览图片
    showImg(e) {
        // 获取当前点击的图片路径
        let imgsrc = e.target.currentSrc;
        // 获取当前图片路径所对应的索引
        let index = this.state.imgList.findIndex((item) => {
            return item === imgsrc
        })
        // alert(1111)
        ImagePreview.open({
            images: this.state.imgList,
            startPosition: index
        })
    }
    changeSku() {
        // 获取子组件实例
        // console.log(this.skuRef.current)
        // 调用子组件方法改变子组件状态
        this.skuRef.current.changeIsShow();
    }
    getSkuInfo() {
        // 获取初始化选择的sku名称、
        let skuName = []
       this.state.skuList.forEach((item, index) => {
            // 获取每个属性默认选择的值
            let attr = this.state.productAttr[index].attrValues[item];
            skuName.push(attr)
        })
        // 处理获取 当前选中sku名称
        skuName = skuName.join(",");
        // 获取sku规格对象
        let productValue = this.state.productValue;
        let skuInfo = productValue[skuName];
        console.log(skuInfo)
        // let msgInfo = {
        //     price:skuInfo.price,
        //     otPrice:skuInfo.otPrice,
        //     sales:skuInfo.sales,
        //     stock:skuInfo.stock,
        //     storeName:this.state.info.storeName,
        //     image:skuInfo.image,
        //     sku:skuInfo.suk
        // }
        this.state.msgInfo.price = skuInfo.price;
        this.state.msgInfo.otPrice = skuInfo.otPrice;
        this.state.msgInfo.sales = skuInfo.sales;
        this.state.msgInfo.stock = skuInfo.stock;
        this.state.msgInfo.storeName = this.state.info.storeName;
        this.state.msgInfo.image = skuInfo.image;
        this.state.msgInfo.sku = skuInfo.suk;
        this.state.msgInfo.productAttrUnique  = skuInfo.id;
        this.state.msgInfo.productId = skuInfo.productId
        this.setState({
            msgInfo:this.state.msgInfo
        })
    }
    //用户收藏
   async userColllet(){
        if(this.state.userCollect){
            // 取消收藏
            let res = await RemoveClolet(this.state.msgInfo.productId);
            if(res.data.code===200){
                Toast.success("取消收藏")
                this.setState({
                    userCollect:false
                })
                return
            }
            Toast.info(res.data.message)
        }else{
            //收藏商品
            let data = {
                category:"product",
                id:this.state.msgInfo.productId
            }
            let res = await userClolet(data);
            if(res.data.code===200){
                Toast.success("收藏成功")
                this.setState({
                    userCollect:true
                })
                return
            }
            Toast.info(res.data.message)
        }
    }
}
export default WithRouter(Info);